package com.lqk.demo.pessimisticlock.syncmode.sequencecontrol.alternately;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author lqk
 * @date 2021/12/23 17:09
 */
@Slf4j
public class TestReentrantLock {
    public static void main(String[] args) throws InterruptedException {
        AwaitSignal awaitSignal = new AwaitSignal(5);
        Condition a = awaitSignal.newCondition();
        Condition b = awaitSignal.newCondition();
        Condition c = awaitSignal.newCondition();

        new Thread(()->{
            awaitSignal.print("a",a,b);
        }).start();
        new Thread(()->{
            awaitSignal.print("b",b,c);
        }).start();
        new Thread(()->{
            awaitSignal.print("c",c,a);
        }).start();

        TimeUnit.SECONDS.sleep(1);
        awaitSignal.lock();
        try{
            System.out.println("开始。。。");
            a.signalAll();
        }finally {
            awaitSignal.unlock();
        }

    }
}
class AwaitSignal extends ReentrantLock{
    private int loopNumber;

    public AwaitSignal(int loopNumber) {
        this.loopNumber = loopNumber;
    }

    // 参数1：打印的内容，参数2：进入哪一间休息室等待, 参数3：下一间休息室
    public void print(String str, Condition current, Condition next){
        for (int i = 0; i < loopNumber; i++) {
            lock();
            try{
                current.await();
                System.out.print(str);
                next.signalAll();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                unlock();
            }
        }
    }
}
